package com.newidea.facillty.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.newidea.facillty.OpcConfiguration;
import com.newidea.facillty.entity.HuaweiOpcTag;
import lombok.extern.slf4j.Slf4j;
import org.openscada.opc.lib.da.Group;
import org.openscada.opc.lib.da.Item;
import org.openscada.opc.lib.da.Server;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * 同步读取某个点位的值
 *
 * @author Freud
 */
@Service
@Slf4j
public class HuaweiOpcService {

    /**
     * 获取换热站opc全部的数据
     */
    public JSONObject getOpcAllTag() throws Exception {
        // 读取json配置的状态
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("facility/huawei/huaweiOpcTag.json");
        if (in == null) {
            throw new RuntimeException("未能读取到配置文件facilityState.json");
        }
        JSONArray opcTagArray = JSONUtil.parseArray(IoUtil.read(in, StandardCharsets.UTF_8));
        log.info("成功读取配置文件huaweiOpcTag.json");
        List<HuaweiOpcTag> huaweiOpcTagList = opcTagArray.toList(HuaweiOpcTag.class);

        // 当前时间
        String now = DateUtil.now();

        // 配置opc服务器
        Server server = new Server(
                OpcConfiguration.getCLSIDConnection(),
                Executors.newSingleThreadScheduledExecutor());
        // 连接连接
        server.connect();
        // 访问组内数据
        Group group = server.addGroup();

        for (HuaweiOpcTag huaweiOpcTag : huaweiOpcTagList) {
            // 设置要访问的tag
            Item item = group.addItem(huaweiOpcTag.getTag());
            // tag对应的值
            huaweiOpcTag.setValue(item.read(false).getValue().getObject());
            // 采集时间
            huaweiOpcTag.setCreateTime(now);
        }
        server.dispose();

        JSONObject result = new JSONObject();
        result.put("opcTagList", huaweiOpcTagList);
        return result;
    }

}
